import { createRouter, createWebHashHistory } from 'vue-router'
import userStore from '../stores/userStore'

// 懒加载组件
const DeviceList = () => import('../components/DeviceList.vue')
const DeviceAdd = () => import('../components/DeviceAdd.vue')
const DeviceShare = () => import('../components/DeviceShare.vue')
const DeviceDetail = () => import('../components/DeviceDetail.vue')
const Login = () => import('../components/Login.vue')
const UserManagement = () => import('../components/UserManagement.vue')

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    name: 'DeviceList',
    component: DeviceList,
    meta: { requiresAuth: true }
  },
  {
    path: '/add',
    name: 'DeviceAdd',
    component: DeviceAdd,
    meta: { requiresAuth: true }
  },
  {
    path: '/share',
    name: 'DeviceShare',
    component: DeviceShare,
    meta: { requiresAuth: true }
  },
  {
    path: '/users',
    name: 'UserManagement',
    component: UserManagement,
    meta: { requiresAuth: true, requiresAdmin: true }
  },
  {
    path: '/device/:id',
    name: 'DeviceDetail',
    component: DeviceDetail,
    meta: { requiresAuth: true },
    props: true
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 检查是否需要认证
  if (to.meta.requiresAuth && !userStore.isLoggedIn.value) {
    return next('/login')
  }
  
  // 检查是否需要管理员权限
  if (to.meta.requiresAdmin && !userStore.isAdmin.value) {
    return next('/')
  }
  
  // 已登录用户访问登录页时重定向到首页
  if (to.path === '/login' && userStore.isLoggedIn.value) {
    return next('/')
  }
  
  next()
})

export default router